package com.zxjbyte.yiyi.module.plugin.monitor.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.unit.DataSizeUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.system.SystemUtil;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.StringTokenizer;

/**
 * 网络工具类
 *
 * @Author zhangxingjia
 * @Date 2024/7/3 11:18
 * @Version: 1.0
 */
@Slf4j
@UtilityClass
public class NetWorkUtil {

    // 网速测速时间2s
    private static final int SLEEP_SECONDS = 2;

    /**
     * 获取网络上下行速度
     * @return
     */
    public Map<String, String> getNetworkUpDownRate() {
        Map<String, String> map = new HashMap<>();
        Process pro = null;
        Runtime runtime = Runtime.getRuntime();
        BufferedReader input = null;
        try {
            boolean isWindows = SystemUtil.getOsInfo().isWindows();
            String command = isWindows ? "netstat -e" : "ifconfig";
            pro = runtime.exec(command);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            long[] result1 = readInLine(input, isWindows);
            Thread.sleep(SLEEP_SECONDS * 1000);
            pro.destroy();
            input.close();
            pro = runtime.exec(command);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            long[] result2 = readInLine(input, isWindows);
            String upSpeed = DataSizeUtil.format(Convert.toLong(NumberUtil.div(NumberUtil.sub(result2[0], result1[0]), SLEEP_SECONDS)));
            String downSpeed = DataSizeUtil.format(Convert.toLong(NumberUtil.div(NumberUtil.sub(result2[1], result1[1]), SLEEP_SECONDS)));
            map.put("UP", upSpeed + (upSpeed.endsWith("B")?"/S":"B/S"));
            map.put("DOWN", downSpeed + (downSpeed.endsWith("B")?"/S":"B/S"));
        } catch (Exception e) {
            log.info(">>> Network speed measurement failed：", e);
        } finally {
            IoUtil.close(input);
            Optional.ofNullable(pro).ifPresent(Process::destroy);
        }
        return map;
    }

    private long[] readInLine(BufferedReader input, boolean isWindows) {
        long[] arr = new long[2];
        StringTokenizer tokenStat;
        try {
            if (isWindows) {
                // 获取windows环境下的网口上下行速率
                input.readLine();
                input.readLine();
                input.readLine();
                input.readLine();
                tokenStat = new StringTokenizer(input.readLine());
                tokenStat.nextToken();
                arr[0] = Long.parseLong(tokenStat.nextToken());
                arr[1] = Long.parseLong(tokenStat.nextToken());
            } else {
                // 获取linux环境下的网口上下行速率
                long rx = 0, tx = 0;
                String line = null;
                //RX packets:4171603 errors:0 dropped:0 overruns:0 frame:0
                //TX packets:4171603 errors:0 dropped:0 overruns:0 carrier:0
                while ((line = input.readLine()) != null) {
                    if (line.contains("RX packets")) {
                        rx += Long.parseLong(line.substring(line.indexOf("RX packets") + 11, line.indexOf(" ",
                                line.indexOf("RX packets") + 11)));
                    } else if (line.contains("TX packets")) {
                        tx += Long.parseLong(line.substring(line.indexOf("TX packets") + 11, line.indexOf(" ",
                                line.indexOf("TX packets") + 11)));
                    }
                }
                arr[0] = rx;
                arr[1] = tx;
            }
        } catch (Exception e) {
            log.error(">>> network speed measurement error：", e);
        }
        return arr;
    }

    public static void main(String[] args) {
        for(int i = 0; i < 100; i++){
            Map<String, String> map = getNetworkUpDownRate();
            System.out.println("第" + i + "次 -> 下载速度：" + map.get("DOWN") + ", 上传速度：" + map.get("UP"));
        }

    }
}
